#include "alp_list.h"
#include "bencode.h"
#include <stdlib.h>


alp_status_t alp_list_create(alp_list_t **newlist)
{

	alp_list_t *list = (alp_list_t*) malloc(sizeof(alp_list_t));
	*newlist = list;
	if (list == 0)
		return ALP_E_MEMORY;
	list->first = list->last = 0;
	return 0;
}

alp_status_t alp_list_append(alp_list_t *list, void *data)
{
	alp_list_index_t *elem = (alp_list_index_t*) malloc(sizeof(alp_list_index_t));
	if (elem == 0)
		return ALP_E_MEMORY; //allocate memory failed and return -1
	elem->data = data;
	elem->next = 0;
	if (list->last)	// assert(list->last->next == 0);
		list->last->next = elem;
	else			// assert(list->last == 0);
		list->first = elem;
	list->last = elem;

	return 0;
}

alp_status_t alp_list_insert(alp_list_t *list, void *data)
{
	alp_list_index_t *elem = (alp_list_index_t*) malloc(sizeof(alp_list_index_t));
	if (elem == 0)
		return ALP_E_MEMORY;
	elem->data = data;
	elem->next = list->first;
	list->first = elem;
	if (list->last == 0)
		list->last = elem;
	return 0;
}

alp_list_index_t * alp_list_first(alp_list_t *list)
{
	return list->first;
}

alp_list_index_t * alp_list_next(alp_list_index_t *li)
{
	return li->next;
}

void alp_list_this(alp_list_index_t *li, void **data)
{
	*data = li->data;
}

void alp_list_destroy(alp_list_t *list)
{
	alp_list_index_t * temp;
	if(list->first == 0)
		return;
	temp = list->first;
	while(temp!= 0)
	{
		list->first = list->first->next;
		alp_bencode_destroy((bencode_node_t*) temp->data );
		temp = list->first;
	}
	free(list);
}

